package com.youth.config.shiro;

import com.youth.entity.po.User;
import com.youth.service.UserService;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;

import java.util.List;

/**
 * @author wuxian
 * @date 2019/12/23 14:21
 */
public class MyRelam extends AuthorizingRealm {

    @Autowired
    private UserService userService;

    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {

        String username = (String) principals.getPrimaryPrincipal();
        SimpleAuthorizationInfo authorizationInfo = new SimpleAuthorizationInfo();
        //获取数据库用户角色
        List<String> roles = userService.getUserRolesByName(username);
        if (!CollectionUtils.isEmpty(roles)) {
            authorizationInfo.addRoles(roles);
        }
        //获取数据库用户权限
        List<String> pression = userService.getUserPressionByName(username);
        if (!CollectionUtils.isEmpty(pression)) {
            authorizationInfo.addStringPermissions(pression);
        }
        return authorizationInfo;
    }

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        //根据token获取用户名
        String username = (String) token.getPrincipal();

        User user = userService.getUserInfoByName(username);
        if (user == null) {
            throw new AuthenticationException("此用户不存在");
        } else {
            SimpleAuthenticationInfo simpleAuthenticationInfo = new SimpleAuthenticationInfo(user, user.getPassword(), getName());
            simpleAuthenticationInfo.setCredentialsSalt(ByteSource.Util.bytes(user.getUsername()));
            return simpleAuthenticationInfo;
        }
    }
}
